package com.zlkj.pro.core.util;

import cn.stylefeng.roses.kernel.config.api.context.ConfigContext;
import com.alibaba.fastjson.JSONObject;
import com.zlkj.pro.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.IDENTITY_AUTHENTICATION_FAILURE;

/**
 * *
 * * @author 孙铭泽
 * * @date 2022-9-21
 * * @time 17:23
 */
@Slf4j
public class IdCardAuditUtil {

    public static void audit(String idcard, String name) {
        String appCode = ConfigContext.me().getConfigValueNullable("THE_SECOND_ELEMENT_APP_CODE", String.class);
        String url = ConfigContext.me().getConfigValueNullable("THE_SECOND_ELEMENT_URL", String.class);
        Map<String, String> params = new HashMap<>();
        params.put("idcard", idcard);
        params.put("name", name);
        try {
            String result = postForm(appCode, url, params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                JSONObject result1 = jsonObject.getJSONObject("result");
                Integer res = result1.getInteger("res");
                if (res != 1) {
                    throw new BusinessException(IDENTITY_AUTHENTICATION_FAILURE, "身份认证失败" + result1.getString("description"));
                }
            } else {
                throw new BusinessException(IDENTITY_AUTHENTICATION_FAILURE, "身份认证失败" + jsonObject.getString("message"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(IDENTITY_AUTHENTICATION_FAILURE);
        }
    }


    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        for (String key : params.keySet()) {
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        assert response.body() != null;
        return response.body().string();
    }

}
